/**
 * Copyright 2006 Brad Reynolds
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.leeloo.databinding.ui.test.support;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

public class SWTNavigator {
    private final Composite composite;

    public SWTNavigator(Composite composite) {
        this.composite = composite;
    }

    private static final Control[] NO_CONTROLS = new Control[0];

    /**
     * Returns all descendants of the provided <code>clazz</code>.
     * 
     */
    public Control[] getDescendantsByType(Class clazz) {
        List controls = new LinkedList();

        Control[] children = composite.getChildren();
        for (int i = 0; i < children.length; i++) {
            Control child = children[i];
            if (child instanceof Composite) {
                Control[] matches = new SWTNavigator((Composite) child).getDescendantsByType(clazz);
                controls.addAll(Arrays.asList(matches));
            }

            if (clazz.equals(child.getClass())) {
                controls.add(child);
            }
        }

        return (Control[]) ((controls.size() > 0) ? controls.toArray(new Control[controls.size()]) : NO_CONTROLS);
    }
}
